<template>
  <el-drawer v-model="visible" title="权限配置" direction="rtl" size="600px" :before-close="handleClose">
    <div class="drawer-content">
      <div class="role-info">
        <h3>{{ roleData.name }}</h3>
        <p>{{ roleData.description }}</p>
      </div>

      <el-divider />

      <div class="permission-section">
        <div class="section-header">
          <h4>权限配置</h4>
          <div class="quick-actions">
            <el-button size="small" @click="selectAll">全选</el-button>
            <el-button size="small" @click="clearAll">清空</el-button>
          </div>
        </div>

        <div class="permission-tree">
          <el-tree ref="permissionTreeRef" :data="permissionTree" :props="treeProps" show-checkbox node-key="code"
            :default-checked-keys="selectedPermissions" :default-expand-all="true" @check="handlePermissionCheck">
            <template #default="{ node, data }">
              <div class="tree-node">
                <span class="node-label">{{ data.name }}</span>
                <el-tag :type="data.type === '模块' ? 'primary' : 'success'" size="small" class="node-type">
                  {{ data.type }}
                </el-tag>
                <span class="node-desc">{{ data.description }}</span>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存配置
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  roleData: {
    type: Object,
    default: () => ({})
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const permissionTreeRef = ref()
const submitting = ref(false)
const selectedPermissions = ref([])

// 权限树配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 模拟权限树数据
const permissionTree = [
  {
    name: '用户管理',
    code: 'user',
    type: '模块',
    description: '用户相关权限',
    children: [
      {
        name: '查看用户',
        code: 'user:view',
        type: '操作',
        description: '查看用户列表和详情'
      },
      {
        name: '编辑用户',
        code: 'user:edit',
        type: '操作',
        description: '编辑用户信息'
      },
      {
        name: '删除用户',
        code: 'user:delete',
        type: '操作',
        description: '删除用户'
      },
      {
        name: '导出用户',
        code: 'user:export',
        type: '操作',
        description: '导出用户数据'
      }
    ]
  },
  {
    name: '内容管理',
    code: 'content',
    type: '模块',
    description: '内容相关权限',
    children: [
      {
        name: '查看内容',
        code: 'content:view',
        type: '操作',
        description: '查看内容列表和详情'
      },
      {
        name: '编辑内容',
        code: 'content:edit',
        type: '操作',
        description: '编辑内容信息'
      },
      {
        name: '删除内容',
        code: 'content:delete',
        type: '操作',
        description: '删除内容'
      },
      {
        name: '发布内容',
        code: 'content:publish',
        type: '操作',
        description: '发布内容'
      },
      {
        name: '审核内容',
        code: 'content:audit',
        type: '操作',
        description: '审核内容'
      }
    ]
  },
  {
    name: '系统管理',
    code: 'system',
    type: '模块',
    description: '系统相关权限',
    children: [
      {
        name: '查看系统',
        code: 'system:view',
        type: '操作',
        description: '查看系统信息'
      },
      {
        name: '编辑系统',
        code: 'system:edit',
        type: '操作',
        description: '编辑系统配置'
      },
      {
        name: '系统配置',
        code: 'system:config',
        type: '操作',
        description: '系统高级配置'
      }
    ]
  },
  {
    name: '角色管理',
    code: 'role',
    type: '模块',
    description: '角色相关权限',
    children: [
      {
        name: '查看角色',
        code: 'role:view',
        type: '操作',
        description: '查看角色列表和详情'
      },
      {
        name: '编辑角色',
        code: 'role:edit',
        type: '操作',
        description: '编辑角色信息'
      },
      {
        name: '删除角色',
        code: 'role:delete',
        type: '操作',
        description: '删除角色'
      }
    ]
  }
]

// 计算属性
const visible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal && props.roleData) {
    // 设置已选中的权限
    selectedPermissions.value = props.roleData.permissions || []

    nextTick(() => {
      // 设置树的选中状态
      permissionTreeRef.value?.setCheckedKeys(selectedPermissions.value)
    })
  }
})

// 方法
const handlePermissionCheck = (data, checked) => {
  // 获取当前选中的权限
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()

  // 合并完全选中和半选中的权限（半选中的是父级权限）
  selectedPermissions.value = [...checkedKeys, ...halfCheckedKeys]
}

const selectAll = () => {
  const allKeys = []

  const collectKeys = (nodes) => {
    nodes.forEach(node => {
      allKeys.push(node.code)
      if (node.children) {
        collectKeys(node.children)
      }
    })
  }

  collectKeys(permissionTree)
  permissionTreeRef.value?.setCheckedKeys(allKeys)
  selectedPermissions.value = allKeys
}

const clearAll = () => {
  permissionTreeRef.value?.setCheckedKeys([])
  selectedPermissions.value = []
}

const handleSubmit = async () => {
  try {
    submitting.value = true

    // 获取最终选中的权限（只要叶子节点）
    const checkedKeys = permissionTreeRef.value.getCheckedKeys(true) // leafOnly: true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    emit('submit', {
      roleId: props.roleData.id,
      permissions: checkedKeys
    })

    ElMessage.success('权限配置成功')
    handleClose()

  } catch (error) {
    console.error('权限配置失败:', error)
    ElMessage.error('权限配置失败')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped lang="scss">
.drawer-content {
  padding: 20px;
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.role-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 20px;

  h3 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 16px;
  }

  p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
}

.permission-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h4 {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }

    .quick-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.permission-tree {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  max-height: 400px;
  overflow-y: auto;

  :deep(.el-tree) {
    padding: 12px;
  }

  .tree-node {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    padding-right: 12px;

    .node-label {
      font-weight: 500;
      color: #333;
    }

    .node-type {
      margin: 0;
    }

    .node-desc {
      color: #666;
      font-size: 12px;
      margin-left: auto;
    }
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

:deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px 20px 16px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-drawer__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-divider) {
  margin: 16px 0;
}
</style>
